package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.mapper.SeckillMapper;
import cn.wolfcode.shop.cloud.mapper.SeckillOrderMapper;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.util.SeckillGoodVO;
import cn.wolfode.shop.cloud.domain.OrderInfo;
import cn.wolfode.shop.cloud.domain.SeckillOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;


    @Override
    public String doSeckillOrder(Long seckillId, Long id) {
        //1、将秒杀当前商品的库存数减一(修改t_seckill_goods中的库存数)
        seckillMapper.updateStockCount(seckillId);
        //2、将秒杀商品的订单详情信息储存到数据库中
        //先new出一个订单实体对象
        OrderInfo orderInfo = new OrderInfo();
        //通过seckillId查询出vo对象
        SeckillGoodVO seckillGoodVO = seckillService.goodDetail(seckillId);
        BeanUtils.copyProperties(seckillGoodVO,orderInfo);
        orderInfo.setUserId(id);
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodCount(seckillGoodVO.getStockCount());
        //通过推特 雪花算法获取订单编号
        String orderNo = IdGenerateUtil.get().nextId()+"";
        orderInfo.setOrderNo(orderNo);
        //储存到数据库中
        orderInfoMapper.insert(orderInfo);
        //3、将一组数据储存到t_seckill_order表中，用于判断当前登录用户是否是多次秒杀
        //new出一个SeckillOrder对象
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(id);
        seckillOrder.setOrderNo(orderNo);
        seckillOrder.setSeckillId(seckillId);
        seckillOrderMapper.insert(seckillOrder);
        //保存到数据库
        return orderNo;
    }

    @Override
    public OrderInfo queryOrderInfo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.queryOrderInfo(orderNo);
        return orderInfo;
    }

    @Override
    public Long changeOrderInfoStatus(String orderNo, Integer statusTimeout) {
        return orderInfoMapper.changeOrderInfoStatus(orderNo,statusTimeout);
    }

    @Override
    public void updateStatus(String out_trade_no, Integer status) {
        orderInfoMapper.updateStatus(out_trade_no,status);
    }
}
